package ch.sv7.tool.dbmanager.db;

import ch.sv7.tool.codec.Codecs;

/**
 * This class encapsulates string data and its format
 *
 * @author svt
 *
 */
public class SafeString {

	public static final String FORMAT_AUTO = "auto";
	public static final String FORMAT_BASE64 = "base64";
	public static final String FORMAT_PLAIN = "plain";
	
	private String safeString;
	private String format;

	public SafeString setOriginalData(String data, String format){
		if (data == null){
			this.format = FORMAT_AUTO;
			safeString = null;
			return this;
		}
		if (!isStringSafe(data)){
			format = FORMAT_BASE64;
		}
		if (FORMAT_AUTO.equals(format) || FORMAT_PLAIN.equals(format)){
			this.format = FORMAT_AUTO;
			this.safeString = data;
		} else if (FORMAT_BASE64.equals(format)){
			this.format = format;
			this.safeString = Codecs.base64Encode(data);
		} 
		return this;
	}
	public SafeString setOriginalData(String data){
		return setOriginalData(data, FORMAT_AUTO);
	}

	public SafeString setOriginalData(byte[] data, String format){
		if (data == null){
			this.format = FORMAT_AUTO;
			safeString = null;
			return this;
		}		
		if (FORMAT_AUTO.equals(format) || FORMAT_BASE64.equals(format)){
			this.format = FORMAT_AUTO;
			safeString = new String(Codecs.base64Encode(data));
		} else if (FORMAT_PLAIN.equals(format)){
			this.format = format;
			safeString = new String(data);
		}
		return this;
	}

	public SafeString setOriginalData(byte[] data){
		return setOriginalData(data, FORMAT_AUTO);
	}
	
	public SafeString setSafeString(String safeString, String format){
		this.safeString = safeString;
		if (format != null){
			this.format = format;
		} else {
			this.format = FORMAT_AUTO;
		}
		return this;
	}
	
	public String getSafeString(){
		return safeString;
	}
	
	public String getOriginalDataAsString(){
		if (safeString == null) {
			return null;
		}
		if (FORMAT_BASE64.equals(format)){
			return Codecs.base64Decode(safeString.trim());
		} else {
			return safeString;
		}
	}

	public byte[] getOriginalDataAsByteArray(){
		if (safeString == null) {
			return null;
		}		
		if (FORMAT_BASE64.equals(format)){
			return Codecs.base64Decode(safeString.trim().getBytes());
		} else {
			return safeString.getBytes();
		}
	}

	public String getFormat() {
		return format;
	}

	private boolean isStringSafe(String str ){
		if (str == null) {
			return true;
		} else {
			for (int i=0; i<str.length(); i++) {
				char c = str.charAt(i);
				if (c == 0){
					return false;
				}
			}
		}
		return true;
	}
	
}
